import request from '@/utils/request'
import { User, Profile, ProfileAction } from '../reducers/profile'
import { RootThunkAction } from '../index'

/**
 * 保存用户信息
 * @param {*} payload
 * @returns
 */
export const saveUserInfo = (payload: User): ProfileAction => {
  return {
    type: 'profile/user',
    payload,
  }
}

/**
 * 获取用户信息
 * @returns Promise
 */
export const getUserInfo = (): RootThunkAction => {
  return async (dispatch) => {
    const res = await request({
      method: 'GET',
      url: '/user',
    })
    // console.log(res);
    dispatch(saveUserInfo(res.data))
  }
}
export const saveUserProfile = (payload: Profile): ProfileAction => {
  return {
    type: 'profile/profile',
    payload,
  }
}
/**
 * 获取编辑用户信息
 * @returns Promise
 */

export const getUserProfile = (): RootThunkAction => {
  return async (dispatch) => {
    const res = await request({
      method: 'GET',
      url: '/user/profile',
    })
    // console.log(res);
    dispatch(saveUserProfile(res.data))
  }
}

type PartralType = Partial<Profile>
export const updateProfile = (data: PartralType): RootThunkAction => {
  return async (dispatch) => {
    await request({
      method: 'PATCH',
      url: '/user/profile',
      data,
    })
    // console.log(res);
    dispatch(getUserProfile())
  }
}
